<?php
require_once 'Database.php';
require_once 'Response.php';

class WeChatAuth {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    // 微信小程序登录
    public function login($code) {
        // 调用微信API获取session_key和openid
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        $params = [
            'appid' => WX_APPID,
            'secret' => WX_SECRET,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        
        $response = $this->httpGet($url . '?' . http_build_query($params));
        $data = json_decode($response, true);
        
        if (isset($data['errcode']) && $data['errcode'] != 0) {
            return ['success' => false, 'message' => '微信登录失败'];
        }
        
        $openid = $data['openid'];
        $session_key = $data['session_key'];
        
        // 查找或创建用户
        $user = $this->db->fetchOne("SELECT * FROM users WHERE openid = ?", [$openid]);
        
        if (!$user) {
            // 创建新用户
            $userId = $this->db->insert('users', [
                'openid' => $openid,
                'session_key' => $session_key,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            $user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
        } else {
            // 更新session_key
            $this->db->update('users', [
                'session_key' => $session_key,
                'updated_at' => date('Y-m-d H:i:s')
            ], 'id = ?', [$user['id']]);
        }
        
        // 生成token
        $token = $this->generateToken($user['id'], $openid);
        
        return [
            'success' => true,
            'data' => [
                'token' => $token,
                'user' => $user
            ]
        ];
    }
    
    // 更新用户信息
    public function updateUserInfo($userId, $userInfo) {
        $data = [
            'nickname' => $userInfo['nickName'] ?? null,
            'avatar' => $userInfo['avatarUrl'] ?? null,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        return $this->db->update('users', $data, 'id = ?', [$userId]);
    }
    
    // 验证token
    public function validateToken($token) {
        if (empty($token)) {
            return false;
        }
        
        // 简单的token验证，实际项目中应该使用JWT
        $tokenData = base64_decode($token);
        $parts = explode('|', $tokenData);
        
        if (count($parts) != 3) {
            return false;
        }
        
        list($userId, $openid, $timestamp) = $parts;
        
        // 检查token是否过期（7天）
        if (time() - $timestamp > 7 * 24 * 3600) {
            return false;
        }
        
        // 验证用户是否存在
        $user = $this->db->fetchOne("SELECT * FROM users WHERE id = ? AND openid = ?", [$userId, $openid]);
        
        return $user ? $user : false;
    }
    
    // 生成token
    private function generateToken($userId, $openid) {
        $tokenData = $userId . '|' . $openid . '|' . time();
        return base64_encode($tokenData);
    }
    
    // 解密微信数据
    public function decryptData($encryptedData, $iv, $openid) {
        // 首先需要获取session_key
        // 这里简化处理，实际项目中应该在登录时保存session_key
        $sessionKey = $this->getSessionKey($openid);
        
        if (!$sessionKey) {
            throw new Exception('无法获取session_key');
        }
        
        $aesKey = base64_decode($sessionKey);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        
        $result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
        
        if (!$result) {
            throw new Exception('解密失败');
        }
        
        $dataObj = json_decode($result, true);
        
        if (!$dataObj) {
            throw new Exception('解密数据格式错误');
        }
        
        // 验证数据完整性
        if ($dataObj['watermark']['appid'] !== WX_APPID) {
            throw new Exception('数据来源验证失败');
        }
        
        return $dataObj;
    }
    
    // 获取session_key
    private function getSessionKey($openid) {
        $user = $this->db->fetchOne("SELECT session_key FROM users WHERE openid = ?", [$openid]);
        return $user ? $user['session_key'] : null;
    }
    
    // HTTP GET请求
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($curl);
        curl_close($curl);
        
        return $response;
    }
    
    // 获取当前用户
    public function getCurrentUser() {
        $headers = getallheaders();
        $token = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }
        
        return $this->validateToken($token);
    }
}
?>